
/** 
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.tompai.neo4j;

import java.io.File;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Result;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;

/**
* @desc: neo4j-tools
* @name: Neo4jCypherJavaAPI.java
* @author: tompai
* @createTime: 2018年12月30日 下午8:47:21
* @history:
* @version: v1.0
*/

public class Neo4jCypherJavaAPI {
	
	private static String db_path="target/neo4j-hello-db";
	
    public static void main(String[] args) {
        //指定 Neo4j 存储路径
        File file = new File(db_path);
        //Create a new Object of Graph Database
        GraphDatabaseService graphDB = new GraphDatabaseFactory().newEmbeddedDatabase(file);
        System.out.println("Server is up and Running");

        try(Transaction tx = graphDB.beginTx()){
            //通过Cypher查询获得结果
            StringBuilder sb = new StringBuilder();
            sb.append("MATCH (john)-[:IS_FRIEND_OF]->(USER)-[:HAS_SEEN]->(movie) ");
            sb.append("RETURN movie");
            Result result = graphDB.execute(sb.toString());
            //遍历结果
            while(result.hasNext()){
                //get("movie")和查询语句的return movie相匹配
                Node movie = (Node) result.next().get("movie");
                System.out.println(movie.getId() + " : " + movie.getProperty("name"));
            }

            tx.success();
            System.out.println("Done successfully");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            graphDB.shutdown();    //关闭数据库
        }
    }
}
